"use strict"

let GamingLP_Claimable          = "0"
let GamingLP_RewardsSeconds     = "0"
let GamingLP_RewardTime         =  0

let balance_cb      = 0
let balance_usdt    = 0
let cbPrice         = 0

function onLogin()
{
    onInitLiquidity();

}

async function onInitLiquidity()
{
    var contractCB      = GetContractERC20(Contract_CB);
    var contractUSDT    = GetContractERC20(Contract_USDT);
    var contractCBAvailable = GetContractERC20(Contract_USDT);

    await RefreshAllow();

    balance_usdt = await contractUSDT.balanceOf(Helper.addressCur);
    balance_usdt = window._ethers.utils.formatUnits(balance_usdt, Contract_Decimals)
    balance_usdt = Helper.Fix2(balance_usdt)

    balance_cb = await contractCB.balanceOf(Helper.addressCur);
    balance_cb = window._ethers.utils.formatUnits(balance_cb, Contract_Decimals)
    balance_cb = Helper.Fix2(balance_cb)


    $("#balance_in" ).html(balance_usdt );
    $("#balance_out").html(balance_cb );

    var contractUNIHelper   = GetContractUNIHelper();
    cbPrice = await contractUNIHelper.getPrice(Contract_UNIV3_NFT);
    cbPrice = window._ethers.utils.formatUnits(cbPrice, Contract_Decimals)
    $("#cbPrice").html( "1 USDT = " + cbPrice );
    $("#cbPrice2").html( Helper.Fix8(Helper.Div("1",cbPrice)) );

    var adPool = await contractUNIHelper["getPool()"]();
    var cbPool = await contractCB.balanceOf(adPool);
    cbPool = Helper.Fix2(window._ethers.utils.formatUnits(cbPool, Contract_Decimals))
    $("#cbPool").html( cbPool );
        
    CheckApproveLoop();
}

async function doApproveToSwap(contractAddr,input_amount,decimals)
{
    const amount = window._ethers.utils.parseUnits(input_amount, decimals)

    const contract = new window._ethers.Contract(contractAddr, Contract_ERC20_Abi, Helper.provider.getSigner());          
    var tx = await contract.approve(Contract_Swap,amount);
    var rel = await tx.wait();
    return new Promise((resolve, reject) => {
        resolve(rel.status);
    })
}

async function onclickApprove(id)
{
    var parent_btn_group = $(".select_name_in");
    var token = parent_btn_group.find("#select_name").html();

    if(token=="CB"){
        var amount = $("#select_amount_in").val();
        var status = await doApproveToSwap(Contract_CB,amount,Contract_Decimals);
        if(status==1) {
            ShowToastr("Success","Approve CB");
            allowCB = amount;
            return;
        }
    }
    if(token=="USDT"){
        var amount = $("#select_amount_in").val();
        var status = await doApproveToSwap(Contract_USDT,amount,Contract_Decimals);
        if(status==1) {
            ShowToastr("Success","Approve USDT");
            allowUSDT = amount;
            return;
        }
    }
    setTimeout("RefreshAllow()", 3000);
    setTimeout("RefreshAllow()", 10000);
}

let allowUSDT = -1;
let allowCB   = -1;
async function RefreshAllow()
{
    var contractCB      = GetContractERC20(Contract_CB);
    var contractUSDT    = GetContractERC20(Contract_USDT);
    if(allowCB==-1){
        allowCB = await contractCB.allowance(Helper.addressCur,Contract_Swap)
        allowCB = window._ethers.utils.formatUnits(allowCB, Contract_Decimals)
    }
    if(allowUSDT==-1){
        allowUSDT = await contractUSDT.allowance(Helper.addressCur,Contract_Swap)
        allowUSDT = window._ethers.utils.formatUnits(allowUSDT, Contract_Decimals)
    }
}

async function CheckApproveLoop()
{
    while(true){
        if(Helper.addressCur!=null){

            var btn_Approve = false;

            var uu = $("#select_amount_in").val();
            if(!isNaN(uu)&&uu!=""&&uu!="0"){
                var parent_btn_group = $(".select_name_in");
                var token = parent_btn_group.find("#select_name").html();
                var allow = allowUSDT;
                if(token=="CB"){
                    allow = allowCB;
                }

                if( Helper.isLessThanOrEqualTo(uu,allow) ){
                    $("#btn_approve").addClass("d-none");
                    btn_Approve = false;
                }
                else {
                    $("#btn_approve").removeClass("d-none");
                    btn_Approve = true;
                }
            }else{
                $("#btn_approve").addClass("d-none");
                btn_Approve = false;
            }

            $("#btn_swap").addClass("disabled");
            if(btn_Approve==false){
                if(!isNaN(uu)&&uu!=""&&uu!="0"){
                    $("#btn_swap").removeClass("disabled");
                }
            }

        }
        await Helper.sleep(1000);
    }
}


async function onclickSwap()
{
    $("#btn_swap").attr('disabled', true);
    setTimeout("$('#btn_swap').attr('disabled', false);", 3000);

    var tokenIn  = $(".select_name_in  #select_name").html();
    var tokenOut = $(".select_name_out #select_name").html();
    var input_amount = $("#select_amount_in").val();
    var input_amountOut = $("#select_amount_out").val();

    if(tokenIn=="CB"){
        tokenIn   = Contract_CB;
        tokenOut = Contract_USDT;
    }
    else{
        tokenOut = Contract_CB;
        tokenIn  = Contract_USDT;
    }

    if( Helper.isGreater(input_amount,$("#balance_in").html()) ){
        ShowToastrError("Error","Insufficient Balance");
        return;
    }

    var select2 = $("#" + "select2-dynamic-option-creation-container").html().replace(/%/g,'');
    select2 = (1-Number.parseFloat(select2) / 100);
    var input_amountOutmin = Number.parseFloat(input_amountOut) * select2
    console.log(select2,input_amountOutmin);

    try{
        var status = await doSwap(tokenIn,tokenOut,input_amount,input_amountOutmin,Contract_Decimals)
        if(status==1){
            ShowToastr("Success","Submit Success");
            
            $("#select_amount_in").val("");
            $("#select_amount_out").val("");
        }
    }
    catch(e){
        console.log(e.message)
        if(e.message.indexOf("execution reverted: Too little received")!=-1){
            ShowToastrError("Error","Slippage Too little");
        }
    }
}

function swap_dropdownitem(e){
    var parent_btn_group = $(e).parents(".media");

    parent_btn_group.find("#select_image").attr("src", $(e).find('.row .col img').attr("src"));
    parent_btn_group.find("#select_name").html($(e).find('.row .col').text().replace(/[\t\r\f\n\s]*/g,''));

    var select_name = "select_name_out"
    if($(parent_btn_group).hasClass("select_name_out")){
        select_name = "select_name_in";
    }
    
    var item = $(e).parents(".dropdown-menu").find(".dropdown-item");
    var e2 = item[0];
    if( item[0] == e ){
        e2 = item[1]
    }
    
    var parent_btn_group2 = $("."+select_name);
    if(parent_btn_group2.find("#select_image").attr("src")!=$(e2).find('.row .col img').attr("src")){
        var value = $("#balance_in").html()
        $("#balance_in" ).html( $("#balance_out").html() );
        $("#balance_out").html( value );

        var value2 = $("#select_amount_in").val()
        $("#select_amount_in" ).val( $("#select_amount_out").val() );
        $("#select_amount_out").val( value2 );
    }

    console.log(select_name)

    parent_btn_group2.find("#select_image").attr("src", $(e2).find('.row .col img').attr("src"));
    parent_btn_group2.find("#select_name").html($(e2).find('.row .col').text().replace(/[\t\r\f\n\s]*/g,''));

}

function onclickchanges(){
    var parent_btn_group2 = $(".select_name_in");

    var item = $(parent_btn_group2).find(".dropdown-item");
    for(var ii=0;ii<item.length;ii++){
        if(parent_btn_group2.find("#select_image").attr("src")!=$(item[ii]).find('.row .col img').attr("src")){
            swap_dropdownitem(item[ii])
            break;
        }
    }

}

function uni_input_change(event){
    var inputID = event.currentTarget.id;
    var value   = $(event.currentTarget).val();

    if(inputID=="select_amount_in"){
        var parent_btn_group = $(".select_name_in");
        var token = parent_btn_group.find("#select_name").html();
        if(token=="USDT"){
            var aa = Helper.Mul(  value, cbPrice );
        }
        else{
            var aa = Helper.Div(  value, cbPrice );
        }

        if( isNaN(aa) ){
            aa = ""
        }
        $("#select_amount_out").val( Helper.Fix2(aa) );
    }
    else
    if(inputID=="select_amount_out") {
        var parent_btn_group = $(".select_name_out");
        var token = parent_btn_group.find("#select_name").html();
        if(token=="USDT"){
            var aa = Helper.Mul(  value, cbPrice );
        }
        else{
            var aa = Helper.Div(  value, cbPrice );
        }

        if( isNaN(aa) ){
            aa = ""
        }
        $("#select_amount_in").val( Helper.Fix2(aa) );
    }

}

function onclickMax(e1,e2){
    $("#"+e2).val( $("#"+e1).html() );
    var event = {}
    event.currentTarget = $("#"+e2)[0]
    uni_input_change( event );
    
    var select2 = $("#" + "select2-" + "dynamic-option-creation" + "-container").html().replace(/%/g,'');
    select2 = (1-Number.parseFloat(select2) / 100);
    console.log(select2);
}

async function ShowAPR()
{
    $.ajax({
        url: Helper.GetServerIP() + "/analytics",
                  dataType: "text",
                  type: "post",
                  data: { address:Helper.addressCur },
                  success: async function (data) {
                    var json = JSON.parse(data);

                    cbPrice = Helper.Div("1",json.cbPrice);
                    $("#cbPrice").html( "1 USDT = " + Helper.FixDecimal(cbPrice,6) );
                    $("#cbPrice2").html( Helper.Fix8(Helper.Div("1",cbPrice)) );                    

                },
                  error: function (err) {
                    console.log(err);
                  }
    });

}

(function($) {
    "use strict"

    // dynamic option
    $('#dynamic-option-creation').select2({
        tags: true
    });

    ShowAPR();

})(jQuery);


